package simtester.server

import org.springframework.dao.DataIntegrityViolationException

class CategoryController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list() {
//		def catlist = Category.list().collect { it.name }
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [categoryInstanceList: Category.list(params), categoryInstanceTotal: Category.count()]
		println "categoryInstanceList in CategoryController =====> " + categoryInstanceList
//		[activeView: 'home', catlist: catlist]
    }

    def create() {
        if (request.method == 'POST') {
            def cat = new Category(name: params.name.toLowerCase())
            cat.save()
			def catlist = cat.list().collect { it.name }
            redirect(controller: 'testRun', action: 'create')

        }
    }

    def save() {
        def categoryInstance = new Category(params)
        if (!categoryInstance.save(flush: true)) {
            render(view: "create", model: [categoryInstance: categoryInstance])
            return
        }

		flash.message = message(code: 'default.created.message', args: [message(code: 'category.label', default: 'Category'), categoryInstance.id])
        redirect(action: "show", id: categoryInstance.id)
    }

    def show() {
        def categoryInstance = Category.get(params.id)
        if (!categoryInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'category.label', default: 'Category'), params.id])
            redirect(action: "list")
            return
        }

        [categoryInstance: categoryInstance]
    }

    def edit() {
        def categoryInstance = Category.get(params.id)
        if (!categoryInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'category.label', default: 'Category'), params.id])
            redirect(action: "list")
            return
        }

        [categoryInstance: categoryInstance]
    }

    def update() {
		def updcatlist = params.updatedcatlist.tokenize(',')
        def currlist = Category.list().collect { it.name }

		def tocreate = updcatlist - currlist
		def toremove = currlist - updcatlist

		tocreate.each {
			new Category(name: it.toLowerCase()).save(failOnError: true)
		}
		
		toremove.each {
			Category.findByName(it.toLowerCase()).delete()
		}

        redirect(controller: 'user', action: 'home')
    }

    def delete() {
        def cat = Category.get(params.id)
        cat.delete()
		return
    }
}
